<template>
  <!-- 页面整体容器：包含查询区域、列表区域以及弹窗 -->
  <div class="user-query-page">
    <!-- 查询条件卡片：模糊账号、角色、部门 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryForm" label-width="80px" class="filter-form" inline>
        <el-form-item label="账号">
          <el-input
            v-model="queryForm.keyword"
            placeholder="支持模糊搜索账号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryForm.roleid" placeholder="请选择角色" clearable filterable>
            <el-option
              v-for="item in roleOptions"
              :key="item.roleid"
              :label="item.rolename"
              :value="item.roleid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader
            v-model="queryForm.departmentid"
            :options="departmentOptions"
            :props="cascaderProps"
            placeholder="请选择部门"
            clearable
            filterable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表卡片：顶部工具条 + 固定高度表格 + 分页 -->
    <el-card class="list-card" shadow="never">
      <div class="table-toolbar">
        <div class="table-title">用户列表</div>
        <el-button type="primary" @click="openCreateDialog">新增用户</el-button>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :height="tableHeight"
          v-loading="loading"
          :empty-text="loading ? '加载中...' : '暂无数据'"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="userName" label="账号" min-width="140" show-overflow-tooltip />
          <el-table-column prop="realName" label="姓名" min-width="120" show-overflow-tooltip />
          <el-table-column prop="roleName" label="角色" min-width="120" show-overflow-tooltip />
          <el-table-column
            prop="departmentName"
            label="部门"
            min-width="140"
            show-overflow-tooltip
          />
          <el-table-column prop="phone" label="手机号" min-width="140" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" width="160">
            <template #default="scope">
              <el-button type="primary" text size="small" @click="openEditDialog(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" text size="small" @click="confirmDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pagination.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px" destroy-on-close>
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="formModel.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="formModel.realname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roleid">
          <el-select v-model="formModel.roleid" placeholder="请选择角色" clearable filterable>
            <el-option
              v-for="item in roleOptions"
              :key="item.roleid"
              :label="item.rolename"
              :value="item.roleid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departmentid">
          <el-cascader
            v-model="formModel.departmentid"
            :options="departmentOptions"
            :props="cascaderProps"
            placeholder="请选择部门"
            clearable
            filterable
            style="width: 100%"
            @change="handleDepartmentChange"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formModel.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formModel.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/Http/http'

interface UserRecord {
  id: number | string | null
  username: string
  realname: string
  roleid: number | string | null
  departmentid: number | string | null
  phone: string
  email: string
}

const tableHeight = 420

// ===================== 页面状态 =====================
const loading = ref(false) // 列表加载状态
const submitLoading = ref(false) // 弹窗提交状态
const dialogVisible = ref(false) // 控制新增/编辑弹窗
const dialogMode = ref<'create' | 'edit'>('create') // 当前弹窗模式
const tableData = ref<UserRecord[]>([]) // 列表数据
const roleOptions = ref<any>([]) // 角色下拉
const departmentOptions = ref<any>([]) // 部门下拉（树形结构）

// ===================== 级联选择器配置 =====================
const cascaderProps = {
  value: 'departmentid',
  label: 'departmentname',
  children: 'children',
  checkStrictly: true, // 可以选择任意一级
  emitPath: false, // 只返回最后一级的值，不返回完整路径
}

// ===================== 查询表单 + 分页 =====================
const queryForm = reactive({
  keyword: '',
  roleid: '',
  departmentid: '',
})

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

type UserForm = UserRecord
const defaultFormState = (): UserForm => ({
  id: null,
  username: '',
  realname: '',
  roleid: null,
  departmentid: null,
  phone: '',
  email: '',
})

const formModel = reactive<UserForm>(defaultFormState())
const formRef = ref<FormInstance>()

const formRules = reactive<FormRules<UserForm>>({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 32, message: '账号长度 3-32 位', trigger: 'blur' },
  ],
  realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  roleid: [{ required: true, message: '请选择角色', trigger: 'change' }],
  departmentid: [{ required: true, message: '请选择部门', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
})

const dialogTitle = computed(() => (dialogMode.value === 'create' ? '新增用户' : '编辑用户'))

// ===================== 数据格式化工具 =====================
const normalizeListResponse = (payload: any) => {
  if (!payload) {
    return { items: [], total: 0 }
  }

  if (Array.isArray(payload)) {
    return { items: payload, total: payload.length }
  }

  if (Array.isArray(payload.listResult)) {
    return {
      items: payload.listResult,
      total: payload.totalcount ?? payload.listResult.length,
    }
  }

  if (Array.isArray(payload.items)) {
    return { items: payload.items, total: payload.total ?? payload.items.length }
  }

  if (Array.isArray(payload.result)) {
    return { items: payload.result, total: payload.totalcount ?? payload.result.length }
  }

  if (payload.data) {
    return normalizeListResponse(payload.data)
  }

  return { items: [], total: 0 }
}

// ===================== 下拉数据 =====================
const fetchRoleOptions = async () => {
  try {
    const { data } = await myaxios.get('api/Users/GetRoles')
    const normalized = data.listResult
    roleOptions.value = normalized
    console.log(roleOptions.value)
  } catch (error) {
    console.error('获取角色下拉失败', error)
    roleOptions.value = []
  }
}

const fetchDepartmentOptions = async () => {
  try {
    // 获取部门数据
    const { data } = await myaxios.get('api/Users/GetDepartments')
    const normalized = data.listResult || []

    // 转换为树形结构（如果后端返回的是平铺数据）
    departmentOptions.value = buildDepartmentTree(normalized)
    console.log('部门树形数据:', departmentOptions.value)
  } catch (error) {
    console.error('获取部门下拉失败', error)
    departmentOptions.value = []
  }
}

// ===================== 列表数据 =====================
const fetchUserList = async () => {
  loading.value = true
  try {
    const { data } = await myaxios.get('api/Users/GetUsers', {
      params: {
        PageIndex: pagination.pageIndex,
        PageSize: pagination.pageSize,
        Username: queryForm.keyword,
        RoleId: queryForm.roleid,
        DepartmentId: queryForm.departmentid,
      },
    })

    const normalized = normalizeListResponse(data?.result ?? data)
    tableData.value = normalized.items as UserRecord[]
    console.log(tableData.value)
    pagination.total = normalized.total ?? 0
  } catch (error) {
    console.error('获取用户列表失败', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchUserList()
}

const handleReset = () => {
  queryForm.keyword = ''
  queryForm.roleid = ''
  queryForm.departmentid = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchUserList()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchUserList()
}

// ===================== 弹窗交互 =====================
const resetFormModel = () => {
  Object.assign(formModel, defaultFormState())
  formRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  resetFormModel()
  dialogVisible.value = true
}

const openEditDialog = (row: UserRecord) => {
  dialogMode.value = 'edit'
  resetFormModel()
  Object.assign(formModel, row)
  dialogVisible.value = true
}

const getOptionName = (list: any, id: string | number | null) => {
  if (id === null || id === undefined || id === '') return ''
  const target = list.find((item: any) => String(item.id) === String(id))
  return target?.name ?? ''
}

// ===================== 部门级联选择处理 =====================
const handleDepartmentChange = (value: any) => {
  console.log('选中的部门ID:', value)
  // value 已经是最后一级的ID（因为 emitPath: false）
  formModel.departmentid = value
}

// 递归查找部门名称（用于显示）
const findDepartmentName = (list: any[], id: string | number | null): string => {
  if (!id || !list) return ''

  for (const item of list) {
    if (String(item.departmentid) === String(id)) {
      return item.departmentname
    }
    if (item.children && item.children.length) {
      const name = findDepartmentName(item.children, id)
      if (name) return name
    }
  }
  return ''
}

// 将平铺数据转换为树形结构（如果后端返回的不是树形）
const buildDepartmentTree = (flatList: any[]): any[] => {
  if (!flatList || !flatList.length) return []

  // 检查是否已经是树形结构
  if (flatList.some((item) => item.children && item.children.length > 0)) {
    return flatList
  }

  const map = new Map()
  const tree: any[] = []

  // 先创建映射
  flatList.forEach((item) => {
    map.set(item.departmentid, { ...item, children: [] })
  })

  // 构建树形结构
  flatList.forEach((item) => {
    const node = map.get(item.departmentid)
    if (item.parentid && map.has(item.parentid)) {
      const parent = map.get(item.parentid)
      parent.children.push(node)
    } else {
      tree.push(node)
    }
  })

  // 清理空children
  const cleanEmptyChildren = (nodes: any[]) => {
    nodes.forEach((node) => {
      if (node.children && node.children.length === 0) {
        delete node.children
      } else if (node.children) {
        cleanEmptyChildren(node.children)
      }
    })
  }
  cleanEmptyChildren(tree)

  return tree
}

// ===================== 新增 / 编辑 / 删除 =====================
const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return

    const payload = {
      ...formModel,
      roleid: formModel.roleid,
      rolename: getOptionName(roleOptions.value, formModel.roleid),
      departmentid: formModel.departmentid,
      departmentname: findDepartmentName(departmentOptions.value, formModel.departmentid),
    }

    submitLoading.value = true
    const request =
      dialogMode.value === 'create'
        ? myaxios.post('/api/Users/CreateUser', payload)
        : myaxios.post('/api/Users/UpdateUser', payload)

    request
      .then((res) => {
        if (res.data?.code === 200 || res.status === 200) {
          ElMessage.success(dialogMode.value === 'create' ? '新增成功' : '更新成功')
          dialogVisible.value = false
          fetchUserList()
        } else {
          ElMessage.error(res.data?.message ?? '操作失败')
        }
      })
      .catch((error) => {
        console.error('保存用户失败', error)
        ElMessage.error('保存失败，请稍后再试')
      })
      .finally(() => {
        submitLoading.value = false
      })
  })
}

const confirmDelete = (row: UserRecord) => {
  if (!row?.id) return
  ElMessageBox.confirm(`确定要删除账号「${row.username}」吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  })
    .then(async () => {
      try {
        await myaxios.delete('/api/Users/DeleteUser', { data: { id: row.id } })
        ElMessage.success('删除成功')
        if (tableData.value.length === 1 && pagination.pageIndex > 1) {
          pagination.pageIndex -= 1
        }
        fetchUserList()
      } catch (error) {
        console.error('删除用户失败', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

// ===================== 响应下拉联动，保持名称字段同步 =====================

// ===================== 生命周期 =====================
onMounted(() => {
  fetchRoleOptions()
  fetchDepartmentOptions()
  fetchUserList()
})
</script>

<style scoped>
.user-query-page {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-card {
  border-radius: 8px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 24px;
}

.list-card {
  border-radius: 8px;
}

.list-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
